/*取值存储在localStorage中的fetch2返回数据*/
if(localStorage.subject == ''){
	document.write('');
	window.location.href = url() + '/htm/index.html';
};
$(function(){
	
	var sub_cont = JSON.parse(localStorage.subject);
	//console.log(sub_cont);
	/*题目and内容*/
	musval('sub-title',sub_cont.object,0);

	/*题目图片*/
	if(sub_cont.object.titleAttachments.length > 0){
		musval('sub-img',sub_cont.object,0);
	}else{
		$('.sub-img').hide();
	}
	/*答案*/
	musval('sub-choice',sub_cont.object,0);

	var allTime = sub_cont.object.allowedTime;  /*题目可用时间接口获取*/
	$('.sub-time span').text('剩余 '+allTime+' 秒');  /*初始化时间*/
	var time = setInterval(function(){          /*题目时间倒计时*/
		if(allTime == 0){
			clearInterval(time);
			$.ajax({
				type:'post',
				url:url() + '/quiz/setAsTimeout',
				data:{
					id:sub_cont.object.quizInstanceId
				},
				dataType:'json',
				success:function(rel,sta,xhr){
					var sessionstatus = xhr.getResponseHeader('redirectStatus');
					
					if(sessionstatus == '302'){
						window.location.href = url() + '/wxuser/goCompleteInfo';
						return false;
					};
					//console.log(rel);
					var rel_obj = JSON.parse(rel.result)
					if(rel.code == 0 && rel_obj.status == 0){
						/*返回答题结果*/
						localStorage.sub_result = rel.result;
						localStorage.subject = '';
						window.location.href = url() + '/htm/subject-error.html';
					}else{
						alert(rel_obj.message)
					}

				},
				error:function(){
					console.log('error')
				}
			})
		}else{
			allTime -- ;
			$('.sub-time span').text('剩余 '+allTime+' 秒');
		}
	},1000);

	$('.sub-choice .row').each(function(){       /*选择答案*/
		$(this).click(function(){
			$(this).find('.col-xs-1').addClass('sub-choice-yes');
			$(this).siblings().find('.col-xs-1').removeClass('sub-choice-yes');
			$('.sub-answer').text('已选（'+ChooseAns($(this).index())+'）')
		})
	});
	/*提交答案*/
	$('.sub-submit button').click(function(){
		var index = $('.sub-choice-yes').parent().index()+1
		if(index <= 0){
			return false;
		};
		$.ajax({
			type:'post',
			url:url() + '/quiz/judge',
			data:{
				instanceId:sub_cont.object.quizInstanceId,
				answer:$('.sub-choice-yes').parent().index()+1,
			},
			dataType:'json',
			success:function(res,sta,xhr){
				var sessionstatus = xhr.getResponseHeader('redirectStatus');
				
				if(sessionstatus == '302'){
					window.location.href = url() + '/wxuser/goCompleteInfo';
					return false;
				};
				var res_obj = JSON.parse(res.result);
				//console.log(res_obj);
				if(res.code == 0 && res_obj.status == 0){
					/*返回答题结果*/
					localStorage.sub_result = res.result;
					if(res_obj.object.correct){
						localStorage.subject = '';
						window.location.href = url() + '/htm/subject-success.html';
					}else{
						localStorage.subject = '';
						window.location.href = url() + '/htm/subject-error.html';
					}
				}else{
					alert(res_obj.message);
				}
			},
			error:function(){
				console.log('error');
			}
		})
	})
	
})